#include <DBUtils.hpp>

#include <cstdio>

std::string uint_to_str(const mysqlpp::sql_int_unsigned num)
{
  char buff[50];
  sprintf(buff, "%u", num);
  return std::string(buff);
}

mysqlpp::sql_varchar escape_str(const mysqlpp::sql_varchar& str)
{
  mysqlpp::sql_varchar result;
  for(size_t i = 0; i < str.length(); ++i) {
    switch( str[i] ) {
    case '\'':
      result += "\\'";
      break;
    case '"':
      result += "\\\"";
      break;
    default:
      result += str[i];
    }
  }
  return result;
}

mysqlpp::Connection* db_create_and_connect(const std::string& db,
					   const std::string& host,
					   const std::string& user,
					   const std::string& pass)
{
  mysqlpp::Connection* conn = new mysqlpp::Connection;
  if ( conn == NULL ) return NULL;
  
  if ( !(conn->connect(db.c_str(), host.c_str(), user.c_str(), pass.c_str()) &&
       conn->query("USE allen;").execute() && 
       conn->query("SET NAMES utf8;").execute()) ) {
    std::cerr << conn->error() << std::endl;

    delete conn;
    return NULL;
  }

  return conn;
}

void db_disconnect_and_delete(mysqlpp::Connection** conn)
{
  if( conn == NULL || *conn == NULL ) return;
  
  (*conn)->disconnect();
  delete (*conn);
  (*conn) = NULL;
}
